/* eslint no-underscore-dangle: 0 */
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Button, Table, Pagination, Icon, Message, Grid, Dialog, Input, Select } from '@alifd/next';
import IceContainer from '@icedesign/container';
import {
  FormBinderWrapper as IceFormBinderWrapper,
  FormBinder as IceFormBinder,
  FormError as IceFormError,
} from '@icedesign/form-binder';
import axios from '../../../../instances/request';
import FoundationSymbol from '@icedesign/foundation-symbol';
import EditorInfoDialog from './EditorInfoDialog';
import { inspectionTypes }from '../../../../conf/inspectionTypeConfig.js';

const { Row, Col } = Grid;

export default class OperationTable extends Component {
  static displayName = 'OperationTable';

  static propTypes = {
    limit: PropTypes.number,
  };

  static defaultProps = {
    limit: 8
  };

  constructor(props) {
    super(props);
    this.state = {
      value: {
        sType: 'all',
        sState: 'all',
      },
      tableData: {
        totalCount: 0,
        pageSize: this.props.limit,
        currentPage: 1,
        list: [],
        __loading: true,
      },
    };
  }

  async addOrUpdateEquipment({ id, equipmentname, description, hours, label, radios, scope, type, weekDay, state, }) {
    let url = id == null || id === undefined ? '/superuser/equipment/add' : '/superuser/equipment/update';
    let res = await axios.post(url,{
      id,
      equipmentname,
      description,
      hours,
      label,
      radios,
      scope,
      state,
      type,
      weekDay,
    }).catch((err) => {
      Message.error(`添加或更新设备接口${err}`);
      return Promise.reject(err);
    });
    console.log("添加或更新设备接口",res);

    let { code, msg } = res.data;
    switch (code) {
      case 0:
        await this.fetchData({ page: this.state.tableData.currentPage });
        break;
      default:
        Message.error(`添加或更新设备接口code${code}`);
        return;
    }
  }

  async deleteEquipment({ id }) {
    let res = await axios.post('/superuser/equipment/delete', {
      id,
    }).catch((err) => {
      Message.error(`删除设备接口${err}`);
      return Promise.reject((err));
    });
    console.log("删除设备接口",res);

    let { code, msg } = res.data;
    switch (code) {
      case 0:
        await this.fetchData({ page: this.state.tableData.currentPage });
        break;
      default:
        Message.error(`删除设备接口code${code}`);
        return;
    }
  }

  async stopEquipment({ id }) {
    let res = await axios.post('/superuser/equipment/stop', {
      id
    }).catch((err) => {
      Message.error(`启用停用设备接口${err}`);
      return Promise.reject((err));
    });
    let { code, msg } = res.data;
    switch (code) {
      case 0:
        await this.fetchData({ page: this.state.tableData.currentPage });
        break;
      default:
        Message.error(`启用停用设备接口code${code}`);
        return;
    }
  }

  async fetchData ({ page }) {
    const tableData = this.state.tableData;
    tableData.__loading = true;

    this.setState({ tableData }, async function() {
      let res = await axios.post('/equipment/list', {
        limit: this.props.limit,
        page: page,
        sStr: this.state.value.sStr,
        sType: this.state.value.sType,
        sState: this.state.value.sState,
        order: 'DESC',
        isAll: true,
      }).catch((err) => {
        Message.error(`设备管理列表接口${err}`);
        return Promise.reject(err);
      });

      console.log("设备管理列表接口", res);

      let { code, msg } = res.data;
      switch (code) {
        case 0:
          let { equipmentList, totalCount, count } = msg;
          const tableData = this.state.tableData;
          tableData.list = equipmentList;
          tableData.totalCount = totalCount;
          tableData.__loading = false;
          this.setState({
            tableData
          });
          break;
        default:
          Message.error(`设备管理列表接口code${code}`);
          return;
      }
    });
  };

  hookEditorInfoDialog(value, disable) {
    value = value || {
      state: true,
    };
    value.disable = !!disable;  // 是否禁止编辑
    if(value.radios){  // 编辑的时候转义一下
      value.radios = value.radios[0] === '正常' ? '正常异常' : '无有';
    }
    EditorInfoDialog.show({
      value: value,
      onOk: (value) => {
        // if(disable) {
        //   return;
        // }
        if(value.radios){  // 添加的时候转义一下
          value.radios = value.radios === '正常异常' ? ['正常', '异常'] : ['无', '有'];
        }
        // 添加数据
        return this.addOrUpdateEquipment({
          id: value.id,
          description: value.description,
          equipmentname: value.equipmentname,
          hours: value.hours,
          label: value.label,
          radios: value.radios,
          scope: value.scope,
          type: value.type,
          weekDay: value.weekDay,
          state: value.state,
        }).then(() => {
          value.id ? Message.success("修改设备成功") : Message.success("添加设备成功");
          EditorInfoDialog.hide();
        });
      },
      onClose: () => {
        EditorInfoDialog.hide();
      },
      onCancel: () => {
        EditorInfoDialog.hide();
      },
    });
  }

  renderTitle = (value, index, record) => {
    return (
      <div style={styles.titleCol}>
        <span style={styles.titleText}>{record.equipmentname}</span>
      </div>
    );
  };

  editItem = (record, e) => {
    e.preventDefault();
    this.hookEditorInfoDialog(record, true);
  };

  deleteItem = (record, e) => {
    e.preventDefault();

    let dialog = Dialog.confirm({
      title: '删除确认',
      content: '您确认删除这一条目吗？',
      onOk: () => {
        return this.deleteEquipment({ id: record.id }).then(() => {
          dialog.hide();
          Message.success("删除成功");
        });
      },
      onCancel: () => {
        dialog.hide();
      },
      onClose: () => {
        dialog.hide();
      }
    });
  };

  stopItem = (record) => {
    let dialog = Dialog.confirm({
      title: record.isStop ? '启用确认' : '停用确认',
      content: record.isStop ? '您确认启用此设备吗？' : '您确认停用此设备吗？',
      onOk: () => {
        return this
          .stopEquipment({ id: record.id })
          .then(() => {
            dialog.hide();
            Message.success(record.isStop ? `设备启用成功` : `设备停用成功`);
        });
      },
      onCancel: () => {
        dialog.hide();
      },
      onClose: () => {
        dialog.hide();
      }
    });
  };

  renderOperations = (value, index, record) => {
    return (
      <div className="operation-table-operation">
        <span
          style={{ color: 'rgba(49, 128, 253, 0.65)', cursor: 'pointer' }}
          onClick={this.editItem.bind(this, record)}
        >
          编辑
        </span>
        <span style={styles.separator}/>
        <span
          style={{ color: 'rgba(49, 128, 253, 0.65)', cursor: 'pointer' }}
          onClick={this.stopItem.bind(this, record)}
        >
          { record.isStop ? '启用' : '停用' }
        </span>
        <span style={styles.separator}/>
        <span
          style={{ color: 'rgba(49, 128, 253, 0.65)', cursor: 'pointer' }}
          onClick={ this.deleteItem.bind(this, record) }
        >
          删除
        </span>
      </div>
    );
  };

  changePage = (currentPage) => {
    const tableData = this.state.tableData;
    tableData.currentPage = currentPage;
    this.setState({
      tableData
    },() => {
      this.fetchData({ page: currentPage });
    });
  };

  addEquipment = () => {
    this.hookEditorInfoDialog();
  };

  renderTypes(value, index, record) {
    let name = '';
    inspectionTypes.forEach((ele) => {
      if( record.type === ele.enName ) {
        name = ele.name;
      }
    });
    return name;
  }

  onFormChange(value) {
    // console.log(value);
  }

  async componentDidMount() {
    await this.fetchData({
      page: 1
    });
  }

  render() {
    const tableData = this.state.tableData;

    return (
      <div className="operation-table">
        <IceContainer style={styles.cardContainer}>
          <Row>
            <Col>
              <div style={{ height: '60px', background: '#EAEBEF' }}>
                <div style={
                  {
                    float: 'left',
                    fontSize: '20px',
                    fontWeight: 'bold',
                    height: '60px',
                    lineHeight: '60px',
                    paddingLeft: '30px',
                  }
                }>
                  <FoundationSymbol type='material' style={{ display: 'inline', verticalAlign: 'middle' }} />
                  <span style={{ display: 'inline', verticalAlign: 'middle' }}>&nbsp;设备管理</span>
                </div>
                <div
                  style={{
                    height: '60px',
                    lineHeight: '60px',
                    float: 'right',
                    marginRight: '20px',
                  }}
                >
                  <Button style={styles.addButton} type='primary' onClick={this.addEquipment}>添加设备</Button>
                </div>
              </div>
            </Col>
          </Row>
          <Row>
            <Col style={{ paddingLeft: '20px' }}>
              <IceFormBinderWrapper
                value={this.state.value}
                onChange={this.onFormChange.bind(this)}
                ref="form"
              >
                <Row>
                  <Col span={6}>
                    <div style={styles.formItem}>
                      <div style={styles.formLabel}>搜索：</div>
                      <IceFormBinder
                        name="sStr"
                      >
                        <Input
                          onPressEnter={this.fetchData.bind(this, { page: 1})}
                          placeholder="请输入"
                        />
                      </IceFormBinder>
                    </div>
                  </Col>
                  <Col span={6}>
                    <div style={styles.formItem}>
                      <div style={styles.formLabel}>类型：</div>
                      <IceFormBinder
                        name="sType"
                      >
                        <Select size="medium"  style={{ width: '200px' }}>
                          {
                            inspectionTypes.map((ele, idx) => {
                              return <Select.Option key={idx} value={ele.enName}>{ele.name}</Select.Option>;
                            })
                          }
                          <Select.Option value={'all'}>
                            全部
                          </Select.Option>
                        </Select>
                      </IceFormBinder>
                    </div>
                  </Col>
                  <Col span={6}>
                    <div style={styles.formItem}>
                      <div style={styles.formLabel}>状态：</div>
                      <IceFormBinder
                        name="sState"
                      >
                        <Select size="medium"  style={{ width: '200px' }}>
                          <Select.Option value={true}>
                            正常
                          </Select.Option>
                          <Select.Option value={false}>
                            故障
                          </Select.Option>
                          <Select.Option value='all'>
                            全部
                          </Select.Option>
                        </Select>
                      </IceFormBinder>
                    </div>
                  </Col>
                  <Col span={3}>
                    <div style={styles.formItem}>
                      <Button
                        type='primary'
                        onClick={this.fetchData.bind(this, { page: 1})}
                      >查询</Button>
                    </div>
                  </Col>
                </Row>
              </IceFormBinderWrapper>
            </Col>
          </Row>
          <Table
            isZebra={true}
            dataSource={tableData.list}
            loading={tableData.__loading}
            className="basic-table"
            hasBorder={false}
            primaryKey="key"
            style={{ padding: '0 20px 0 20px' }}
          >
            <Table.Column
              title="设备类别"
              width={200}
              dataIndex={"scope"}
            />
            <Table.Column
              title="设备明细"
              cell={this.renderTitle}
              width={200}
            />
            <Table.Column
              title="描述"
              dataIndex="description"
              width={200}
            />
            <Table.Column
              title="当前状态"
              dataIndex="state"
              width={150}
              cell={(value, index, row) => {
                return row.state ? '正常' : '故障';
              }}
            />
            <Table.Column
              title="值日班组"
              width={150}
              cell={(value, index, row) => {
                if(row.type === 'it' || row.type === 'workstation') {
                  return row.label;
                }
              }}
            />
            <Table.Column
              title="检查时间"
              width={320}
              cell={(value, index, row) => {
                if (row.type === 'it' || row.type === 'workstation') {  // week
                  let week = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];
                  let weekDay = row.weekDay;
                  weekDay.sort((a, b) => {
                    return a > b ? 1 : -1;
                  });
                  const weekDaysDom = [];
                  for( let i=0; i<weekDay.length; i+=3 ) {
                    let w1 = (weekDay[i] || -1) - 1;     // 如果weekDay[i]为0，则也会判定为false = - =
                    let w2 = (weekDay[i + 1] || -1) - 1;
                    let w3 = (weekDay[i + 2] || -1) - 1;
                    weekDaysDom.push(
                      <tr key={i}>
                        <td style={{ padding: '0 10px 2px 0', border:'none' }}>
                          {week[w1]}
                        </td>
                        <td style={{ padding: '0 10px 2px 0', border:'none' }}>
                          {week[w2]}
                        </td>
                        <td style={{ padding: '0 10px 2px 0', border:'none' }}>
                          {week[w3]}
                        </td>
                      </tr>
                    );
                  }

                  return (
                    <div style={{ height: '20px', overflowY: 'auto' }}>
                      {
                        weekDaysDom
                      }
                    </div>
                  );
                  // todo: 如果这里不加上day % 7，后端在设置的时候又没检查用户的输入，就有可能遭到攻击导致整个页面不能用！
                  // todo: 比如用户自己写添加设备请求，weekdays数组多写一个[1,2,...,8]，这里就会报错，而且是所有用户的这个页面都报错！
                  // todo: 可见后端对用户输入做好严格限制的重要性以及代码的健壮性（明知正常不会出错，但是我就是不相信你数据返回是正确的）
                  // todo: 一个系统的输入（对于后端来说是前端请求和数据库返回，对于前端来说是后端返回和用户输入）一定要进行严格限制和检查！这就是所谓程序的健壮性！
                  {/*return <div key={idx}>*/}
                  {/*{['周一', '周二', '周三', '周四', '周五', '周六', '周日'][(day - 1) % 7]}*/}
                  {/*</div>;*/}

                } else {
                  let hours = row.hours;
                  const hoursDom = [];
                  for( let i=0; i<hours.length; i+=3 ) {
                    let h1 = (hours[i] !== null && hours[i] !== undefined) ? `${Math.floor(hours[i])}${hours[i] - Math.floor(hours[i]) === 0.5 ? ':30' : ':00'}` : null;
                    let h2 = (hours[i+1] !== null && hours[i+1] !== undefined) ? `${Math.floor(hours[i+1])}${hours[i+1] - Math.floor(hours[i+1]) === 0.5 ? ':30' : ':00'}` : null;
                    let h3 = (hours[i+2] !== null && hours[i+2] !== undefined) ? `${Math.floor(hours[i+2])}${hours[i+2] - Math.floor(hours[i+2]) === 0.5 ? ':30' : ':00'}` : null;
                    hoursDom.push(
                      <tr key={i}>
                        <td style={{ padding: '0 10px 2px 0', border:'none' }}>
                          {h1}
                        </td>
                        <td style={{ padding: '0 10px 2px 0', border:'none' }}>
                          {h2}
                        </td>
                        <td style={{ padding: '0 10px 2px 0', border:'none' }}>
                          {h3}
                        </td>
                      </tr>
                    );
                  }
                  return (
                    <div style={{ height: '20px', overflowY: 'auto' }}>
                      {
                        hoursDom
                      }
                    </div>
                  );
                }
              }}
            />
            <Table.Column
              title="所属检查单"
              width={320}
              cell={this.renderTypes}
            />
            <Table.Column
              title="操作"
              width={250}
              cell={this.renderOperations}
            />
          </Table>
          <div style={styles.paginationContainer}>
            <Pagination
              current={tableData.currentPage}
              pageSize={this.props.limit}
              total={tableData.totalCount}
              onChange={this.changePage}
              hideOnlyOnePage={true}
            />
          </div>
        </IceContainer>
      </div>
    );
  }
}

const styles = {
  cardContainer: {
    padding: '0 0 20px 0'
  },
  titleCol: {
    display: 'flex',
    flexDirection: 'row',
  },
  titleText: {
    marginLeft: '10px',
    lineHeight: '20px',
  },
  operBtn: {
    display: 'inline-block',
    width: '24px',
    height: '24px',
    borderRadius: '999px',
    color: '#929292',
    background: '#f2f2f2',
    textAlign: 'center',
    cursor: 'pointer',
    lineHeight: '24px',
    marginRight: '6px',
  },
  separator: {
    margin: '0 4px',
    display: 'inline-block',
    height: '12px',
    width: '1px',
    verticalAlign: 'middle',
    background: '#e8e8e8',
  },
  paginationContainer: {
    textAlign: 'right',
    paddingTop: '26px',
    paddingRight: '20px',
  },
  operationTableTitle: {
    fontSize: '18px',
    fontWeight: 'bold',
    fontColor: 'black',
    height: '32px',
    lineHeight: '30px',
    margin: '20px 0 20px 20px',
    paddingLeft: '12px',
    borderLeft: '4px solid rgb(102, 102, 102)',
  },
  addButton: {
  },
  formItem: {
    display: 'flex',
    alignItems: 'center',
    margin: '20px 0px 20px 10px',
  },
  formLabel: {
    minWidth: '60px',
  },
};
